package com.qrxl.common;

import com.qrxl.common.exception.CustomException;
import com.qrxl.util.EnumUtil;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author friday
 * @desc 校验枚举值有效性
 */
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = EnumValue.Validator.class)
public @interface EnumValue {
    String message() default "{枚举值错误}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};


    Class<? extends Enum<?>> enumClass();

    class Validator implements ConstraintValidator<EnumValue, Object> {

        private Class<? extends Enum<?>> enumClass;

        @Override
        public void initialize(EnumValue enumValue) {
            enumClass = enumValue.enumClass();
        }

        @Override
        public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
            if (value == null) {
                return Boolean.TRUE;
            }
            if (enumClass == null) {
                return Boolean.FALSE;
            }

            try {
                if (EnumUtil.findEnum(enumClass, Integer.valueOf(value.toString())) == null) {
                    throw new CustomException(enumClass.getName() + "值错误");
                }
                return Boolean.TRUE;
            } catch (Exception e) {
                return Boolean.FALSE;
            }
        }

    }
}
